package cn.itcast.bos.service.take_delivery.impl;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixAreaRepository;
import cn.itcast.bos.dao.base.OrderRepository;
import cn.itcast.bos.dao.base.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.util.Date;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private FixAreaRepository fixAreaRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    WorkBillRepository workBillRepository;

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;


    @Override
    public void saveOrder(Order order) {
        System.out.println(order);

        order.setOrderNum(UUID.randomUUID().toString()); // 设置订单号
        order.setOrderTime(new Date());// 设置下单时间
        order.setStatus("1"); // 待取件

        // 寄件人 省市区
        Area area = order.getSendArea();
        Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(
                area.getProvince(), area.getCity(), area.getDistrict());
        // 收件人 省市区
        Area recArea = order.getSendArea();
        Area persistRecArea = areaRepository
                .findByProvinceAndCityAndDistrict(recArea.getProvince(),
                        recArea.getCity(), recArea.getDistrict());
        order.setSendArea(persistArea);
        order.setRecArea(persistRecArea);


        String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/findFixedAreaIdByAddress?address="
                + order.getSendAddress()).accept(MediaType.APPLICATION_JSON).get(String.class);
        if (fixedAreaId != null){
            FixedArea one = fixAreaRepository.findOne(fixedAreaId);
            Courier courier = one.getCouriers().iterator().next();
            if (courier != null){
                System.out.println("根据地址匹配分单成功..");
                order.setCourier(courier);//将快递员保存至订单
                //生成uuid订单号 保存订单
                order.setOrderNum(UUID.randomUUID().toString());
                order.setOrderType("1");
                orderRepository.save(order);
                //生成工单，发送短信
                generateWorkBill(order);
                return;
            }
        }
        //通过省市区查询关键字和辅助关键字，实现自动下单
        Area sendArea = order.getSendArea();
        Area byProvinceAndCityAndDistrict = areaRepository.findByProvinceAndCityAndDistrict
                (sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());

        for (SubArea sa:byProvinceAndCityAndDistrict.getSubareas()) {
            //判断提交订单的详细区域是否包含关键字和辅助关键字
            if (order.getSendAddress().contains(sa.getKeyWords())||order.getSendAddress().contains(sa.getAssistKeyWords())){
                Courier courier = sa.getFixedArea().getCouriers().iterator().next();
                if (courier !=null){
                    order.setCourier(courier);//将快递员保存至订单
                    //生成uuid订单号 保存订单
                    order.setOrderNum(UUID.randomUUID().toString());
                    order.setOrderType("1");
                    orderRepository.save(order);
                    //生成工单，发送短信
                    generateWorkBill(order);
                    return;
                }
            }
        }
        // 进入人工分单
        order.setOrderType("2");
        orderRepository.save(order);

    }

    @Override
    public Order findByOrderNum(String orderNum) {
        Order byOrderNum = orderRepository.findByOrderNum(orderNum);
        return byOrderNum;
    }

    //生成工单，发送短信的方法
    private void generateWorkBill(final Order order){
// 生成工单
        WorkBill workBill = new WorkBill();
        workBill.setType("新");
        workBill.setPickstate("新单");
        workBill.setBuildtime(new Date());
        workBill.setRemark(order.getRemark());
        final String smsNumber = RandomStringUtils.randomNumeric(4);
        workBill.setSmsNumber(smsNumber); // 短信序号
        workBill.setOrder(order);
        workBill.setCourier(order.getCourier());
        workBillRepository.save(workBill);

        // 调用MQ服务，发送一条消息
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone", order.getCourier()
                        .getTelephone());
                mapMessage.setString(
                        "msg",
                        "短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
                                + ",联系人:" + order.getSendName() + ",手机:"
                                + order.getSendMobile() + "，快递员捎话："
                                + order.getSendMobileMsg());
                return mapMessage;
            }
        });
        // 修改工单状态
        workBill.setPickstate("已通知");


    }



}
